# -*- coding:utf-8 -*-

import json
from Queue import Queue, Full
from threading import Thread
from utils import DbSession
from plugin.Commplugin import MonitorTask
from plugin.SendEmail import Com63Mail

class QuitTask(object):pass

class Monitor(Thread):
    
    def __init__(self, alarm, scheduler):
        Thread.__init__(self)
        self.taskq = Queue(1000)
        self.jobs = []
        self.alarm = alarm
        self.scheduler = scheduler


    def extractdescr(self, rec):
        srvid = rec[0]
        srvtype = rec[1]
        srvdescr = json.loads(rec[2])
        srvretrycount = rec[6] 

        srvdescr["id"] = srvid
        srvdescr["checkinterval"] = rec[4]
        srvdescr["retrycount"] = srvretrycount
        srvdescr["servicetype"] = srvtype

        return srvtype, srvdescr

    def init(self):
        '''从数据库中读取需要执行监控的任务并启动'''

        with DbSession() as session:
            allservice = session.selectall("select * from m_services")
            for srv in allservice:
                srvtype, srvdescr = self.extractdescr(srv)
                # srvid = srv[0]
                # srvtype = srv[1]
                # srvdescr = json.loads(srv[2])
                # srvretrycount = srv[6] 

                # srvdescr["id"] = srvid
                # srvdescr["checkinterval"] = srv[4]
                # srvdescr["retrycount"] = srvretrycount
                # srvdescr["servicetype"] = srvtype

                job = MonitorTask.start(srvtype, srvdescr, self.alarm, self.scheduler)
                self.jobs.append(job)

    def schedule(self, taskid):
        try:
            self.taskq.put_nowait(taskid)
        except Full:
            print("taskqueue full error")

    def gettask(self, taskid):

        with DbSession() as session:
            srv = session.selectone("select * from m_services where id=%s", (taskid, ))
            return self.extractdescr(srv)
            # srvid = srv[0]
            # srvtype = srv[1]
            # srvdescr = json.loads(srv[2])
            # srvretrycount = srv[6] 

            # srvdescr["id"] = srvid
            # srvdescr["checkinterval"] = srv[4]
            # srvdescr["retrycount"] = srvretrycount
            # srvdescr["servicetype"] = srvtype

            # return srvtype, srvdescr

    def stopjobs(self):
        for job in self.jobs:
            job.unschedule()

        self.jobs = []

    def run(self):
        '''start all service and schedule new task'''

        self.init()
        print("monitor started......")
        while 1:
            self.scheduler.print_jobs()
            taskid = self.taskq.get()
            if isinstance(taskid, QuitTask):
                self.stopjobs()
            else:
                tasktype,task = self.gettask(taskid)
                job = MonitorTask.start(tasktype, task, self.alarm, self.scheduler)
                self.jobs.append(job)
        print("monitor task exited!")        

class AlarmTask(Thread):
    '''告警任务'''

    def __init__(self):
        Thread.__init__(self)
        self.taskq = Queue(1000)

    def send(self, alarminfo):
        try:
            self.taskq.put_nowait(alarminfo)
        except Full:
            print("alarm queue full error")

    def init(self):
        pass

    def run(self):
        print("Alarmtask started......")
        while 1:
            alarm = self.taskq.get()
            if isinstance(alarm, QuitTask):
                break
            else:
                context = {"to":["qinjiandong2010@gmail.com"],"body":alarm}
                EmailNotify(context).notify()
                print("send notify to somebody")


class Notify(object):
    '''decision'''

    def __init__(self, context):
        pass

    def notify(self):
        pass

class EmailNotify(object):
    '''
    发送邮件通知
    要素: 
        1. 收件人 固定为管理员
        2. 通知内容
    '''

    def __init__(self, context):
        self.to = context["to"]
        self.body = context["body"]

    def notify(self):
        print("product email message to %s , %s" % (self.to, self.body))
        subject = 'Cloudmonitor service'
        content = self.body
        com163 = Com63Mail()
        lsCc = []
        accessory = []
        com163.send(subject, content, self.to, lsCc, accessory)

